/**
 * 
 */
package com.sj.szxy.genetic.algorithm.basic;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;

import javax.swing.text.rtf.RTFEditorKit;

/**
 * @author Yi Ping
 * @date 2018年4月3日 下午7:01:39 
 * @since 1.0.0
 *
 */
public class Population {
	
	private Individual population[];
	private double fitness = -1f;
	
	public Population(int size) {
		this.population = new Individual[size];
	}
	
	public Population(int size, int chromosomeLength) {
		this.population = new Individual[size];
		for(int indicidualCount =0; indicidualCount < size; indicidualCount ++) {
			Individual individual = new Individual(chromosomeLength);
			this.population[indicidualCount] = individual;
		}
	}
	
	/**
	 * 
	 * @return
	 */
	public Individual[] getIndividuals() {
		return this.population;
	}
	

	public Individual getFittest(int offset) {
		Arrays.sort(this.population, new Comparator<Individual>() {

			@Override
			public int compare(Individual o1, Individual o2) {
				if(o1.getFitness() > o2.getFitness())
					return -1;
				else if(o1.getFitness() < o2.getFitness())
					return 1;
				return 0;
			}
			
		});
		
		return this.population[offset];
	}
	
	public void setPopulationFitness(double fitness) {
		this.fitness = fitness;
	}
	
	public double getPopulationFitness() {
		return this.fitness;
	}
	
	public int size() {
		return this.population.length;
	}
	
	public Individual setIndividual(int offset,Individual individual) {
		return population[offset] = individual;
	}
	
	public Individual getIndividual(int offset) {
		return population[offset];
	}
	
	public void shuffle() {
		Random random = new Random();
		for(int i = population.length - 1; i> 0 ; i-- ) {
			int index = random.nextInt(i + 1);
			Individual a = population[index];
			population[index] = population[i];
			population[i] = a;
		}
		
	}
}	
